package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AttributeMapper;
import cn.tedu.csmall.product.mapper.AttributeTemplateMapper;
import cn.tedu.csmall.product.pojo.dto.AttributeDTO;
import cn.tedu.csmall.product.pojo.vo.AttributeListItemVO;
import cn.tedu.csmall.product.pojo.vo.AttributeStandardVO;
import cn.tedu.csmall.product.service.AttributeService;
import cn.tedu.csmall.product.web.ServiceCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 程旭东
 */
@Service
public class AttributeServiceImpl implements AttributeService {
    @Autowired
    private AttributeMapper attributeMapper;


    @Override
    public void addNewAttr(AttributeDTO attributeDTO) {
        //归属同一个属性模板的情况下，属性名称必须唯一
        Long templateId = attributeDTO.getTemplateId();
        String name = attributeDTO.getName();
        int result = attributeMapper.selectByAttrTempIdAndName(templateId,name);
        if(result!=0){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"添加相册失败，尝试添加的属性名称在当前属性模板下已经被占用！");
        }
        attributeMapper.addNewAttr(attributeDTO);
    }

    @Override
    public List<AttributeListItemVO> listByTemplateId(Long templateId) {
        List<AttributeListItemVO> attributeListItemVOS = attributeMapper.selectByAttrTempId(templateId);
        return attributeListItemVOS;
    }

    @Override
    public void deleteById(Long id) {
        AttributeStandardVO standardVO = attributeMapper.selectById(id);
        if(standardVO == null){
            throw new ServiceException(ServiceCode.ERR_DELETE,"删除失败，数据库中不存在该属性值");
        }
        attributeMapper.deleteById(id);
    }
}
